#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'Ma.YL'
from Spider import DvisionData
from Dvision import Dvision
import json
import sys
import getopt


def ChineseDvision(full=True, filename="city.min.js"):
    dvisions = DvisionData()
    dictDvision = dvisions.GetAllDvisionData()
    provinces = dict((k, v) for (k, v) in dictDvision.items() if (k[2:] == "0000"))
    Dvisions = []
    for key in sorted(provinces):
        dvision = Dvision(key, provinces.get(key), "")
        proDict = dvision.obj2dict(full)
        cityDvision = dvision.GetSubDvision(dictDvision)
        if len(cityDvision) > 0:
            cityList = [(lambda x: x.obj2dict(full))(x) for x in cityDvision]
            citys = []
            for k in sorted(cityDvision):
                # dvision = Dvision(k.get("code"),k.get("name"),k.get("pcode"))
                dvision = k
                cityDict = dvision.obj2dict(full)
                distDvision = dvision.GetSubDvision(dictDvision)
                #distDvision = sorted(dvision.GetSubDvision(dictDvision),key=lambda x:x.obj2dict(True).get('code'))
                if len(distDvision) > 0:
                    distList = [(lambda x: x.obj2dict(full))(x) for x in distDvision]
                    cityDict["counties"] = distList
                else:
                    pass
                citys.append(cityDict)
            proDict["cities"] = citys
        Dvisions.append(proDict)
    data = {"provinces": Dvisions}
    with open(filename, 'w') as f:
        reload(sys)
        sys.setdefaultencoding('utf-8')
        json.dump(data, f, ensure_ascii=False)


def main(argv):
    fullInfo = False
    outputfile = 'city.min.js'
    try:
        opts, args = getopt.getopt(argv, "hf:n:", ["full=", "name="])
    except getopt.GetoptError:
        print 'RenderDvisionCN.py -f <Y|y|N|n> -n <filename>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'RenderDvisionCN.py -f <Y|y|N|n> -n <filename>'
            sys.exit()
        elif opt in ("-f", "--full"):
            fullInfo = True if arg.lower() == 'y' else False
        elif opt in ("-n", "--name"):
            outputfile = arg
    ChineseDvision(fullInfo,outputfile)


if __name__ == "__main__":
    main(sys.argv[1:])
    print u"文件已生成!"
